package com.smzd.framework.config.authentications;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import com.smzd.framework.utils.AuthCode;

public class CaptchaUsernamePasswordAuthenticationFilter extends
        UsernamePasswordAuthenticationFilter {
    public static final String SPRING_SECURITY_FORM_CAPTCHA_KEY = "j_captcha";
    private String captchaParameter = SPRING_SECURITY_FORM_CAPTCHA_KEY;
    
    private AuthCode authCode;
    
    
    public CaptchaUsernamePasswordAuthenticationFilter(){
        super();
    }
    public CaptchaUsernamePasswordAuthenticationFilter(String loginUrl){
        this.setFilterProcessesUrl(loginUrl);
    }
    
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request,
            HttpServletResponse response) throws AuthenticationException {
        String captcha = obtainCaptcha(request);
        validateCaptcha(captcha, request);
        return super.attemptAuthentication(request, response);
    }
    
    public String getCaptchaParameter() {
        return captchaParameter;
    }
    public void setCaptchaParameter(String captchaParameter) {
        this.captchaParameter = captchaParameter;
    }
    
    public String obtainCaptcha(HttpServletRequest request){
        return request.getParameter(captchaParameter);
    }
    
    public void validateCaptcha(String captcha, HttpServletRequest request){
        System.out.println("---->validateCaptcha!! pass!!");
        HttpSession session = request.getSession(false);
        if(session!=null){
            String captchaInSession = (String)session.getAttribute(authCode.getSessionKey());
            if(!StringUtils.isEmpty(captchaInSession)&&captchaInSession.equalsIgnoreCase(captcha)){
                return;
            }
        }
        throw new AuthenticationServiceException("验证码不正确");  
    }
    public AuthCode getAuthCode() {
        return authCode;
    }
    public void setAuthCode(AuthCode authCode) {
        this.authCode = authCode;
    }
}
